/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.Job;
import entity.PurchaseItem;
import entity.PurchaseOrder;
import entity.Quotation;
import entity.SalesOrder;
import entity.TrackingItem;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Wx
 */
@Stateless
public class SalesOrderSessionBean implements SalesOrderSessionBeanLocal, SalesOrderSessionBeanRemote {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<SalesOrder> getSalesOrders() {
        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s");

        ArrayList<SalesOrder> salesOrders = new ArrayList<SalesOrder>();

        for (Object o : query.getResultList()) {
            SalesOrder s = (SalesOrder) o;

            salesOrders.add(s);
        }

        return salesOrders;
    }

    @Override
    public List<SalesOrder> getSalesOrdersByCustomer(Long custId) {
        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s");

        ArrayList<SalesOrder> salesOrders = new ArrayList<SalesOrder>();

        for (Object o : query.getResultList()) {
            SalesOrder s = (SalesOrder) o;

            if (s.getJob().getCustomer().getCustId().compareTo(custId) == 0) {
                salesOrders.add(s);
            }
        }

        return salesOrders;
    }

    @Override
    public SalesOrder getSalesOrderByPO(Long id) {
        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s");

        for (Object o : query.getResultList()) {
            SalesOrder s = (SalesOrder) o;
            System.out.println("s: " + s);
            System.out.println("s.getJob: " + s.getJob());
            System.out.println("s.getJob.getPurchaseOrder(): " + s.getJob().getPurchaseOrder());
            if (s.getJob().getPurchaseOrder().getId().compareTo(id) == 0) {
                return s;
            }
        }

        return null;
    }

    @Override
    public void updateSalesOrder(Long id, TrackingItem ti) {
        SalesOrder so = entityManager.find(SalesOrder.class, id);

        List<TrackingItem> trackingItems = so.getTrackingItems();

        trackingItems.add(ti);

        so.setTrackingItems(trackingItems);

        entityManager.persist(so);
        entityManager.flush();
    }

    @Override
    public List<PurchaseItem> getPurchaseItemsByStatus(String status) {
        Query query = entityManager.createQuery("SELECT p FROM PurchaseItem p ");

        List<PurchaseItem> temp = new ArrayList<PurchaseItem>();

        for (Object o : query.getResultList()) {
            PurchaseItem pi = (PurchaseItem) o;

            if (pi.getStatus().equals(status)) {
                temp.add(pi);
            }
        }

        return temp;
    }

    @Override
    public PurchaseOrder getPurchaseOrderByPurchaseItem(Long id) {
        Query query = entityManager.createQuery("SELECT p FROM PurchaseOrder p ");

        for (Object o : query.getResultList()) {
            PurchaseOrder po = (PurchaseOrder) o;

            for (PurchaseItem pi : po.getPurchaseItems()) {
                if (pi.getId() == id) {
                    return po;
                }
            }
        }

        return null;
    }

    @Override
    public List<PurchaseOrder> getPurchaseOrders(String status) {
        ArrayList al = new ArrayList();

        Query query = entityManager.createQuery("SELECT p FROM PurchaseOrder p WHERE "
                + "p.status = :instatus ORDER BY p.poDate DESC");
        query.setParameter("instatus", status);

        for (Object o : query.getResultList()) {
            PurchaseOrder po = (PurchaseOrder) o;

            al.add(po);
        }

        return al;
    }

    @Override
    public List<SalesOrder> getSalesOrders(String status) {
        ArrayList al = new ArrayList();

        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s WHERE "
                + "s.status = :instatus ORDER BY s.creationDate DESC");
        query.setParameter("instatus", status);

        for (Object o : query.getResultList()) {
            SalesOrder so = (SalesOrder) o;

            al.add(so);
        }

        return al;
    }

    @Override
    public List<PurchaseOrder> getPurchaseOrders(Long customerId, String status) { //get purchase orders based on customerId and status
        ArrayList al = new ArrayList();

        Query query = entityManager.createQuery("SELECT p FROM PurchaseOrder p WHERE "
                + "p.status = :instatus ORDER BY p.poDate DESC");
        query.setParameter("instatus", status);

        for (Object o : query.getResultList()) {
            PurchaseOrder po = (PurchaseOrder) o;

            if (po.getCustomer().getCustId() == customerId) {
                al.add(po);
            }
        }

        return al;
    }

    @Override
    public List<PurchaseOrder> getPurchaseOrders(String userId, String status) { //get purchase orders based on userId and status
        ArrayList al = new ArrayList();

        Query query = entityManager.createQuery("SELECT p FROM PurchaseOrder p WHERE "
                + "p.status = :instatus ORDER BY p.poDate DESC");
        query.setParameter("instatus", status);

        for (Object o : query.getResultList()) {
            PurchaseOrder po = (PurchaseOrder) o;

            if (po.getCustomer().getEmployee().getUserId().equals(userId)) {
                al.add(po);
            }
        }

        return al;
    }

    @Override
    public void addSalesOrder(Long jobId, String creditCheck, String atpCheck, String status, String remark) {
        Calendar cal = Calendar.getInstance();
        Timestamp ts = new Timestamp(cal.getTime().getTime());

        SalesOrder so = new SalesOrder();

        Job j = entityManager.find(Job.class, jobId);

        so.setJob(j);
        so.setCreditCheck(creditCheck);
        so.setAtpCheck(atpCheck);
        so.setCreationDate(ts);
        so.setStatus(status);
        so.setRemark(remark);

        entityManager.persist(so);
        entityManager.flush();
    }

    @Override
    public void updateQuotation(Long id, String status) {
        Quotation temp = entityManager.find(Quotation.class, id);

        temp.setStatus(status);

        entityManager.persist(temp);
        entityManager.flush();
    }

    @Override
    public void updateSalesOrder(Long id, String status) {
        SalesOrder so = entityManager.find(SalesOrder.class, id);

        so.setStatus(status);

        entityManager.persist(so);
        entityManager.flush();
    }

    @Override
    public ArrayList<Job> getJobs(Integer selectedMonth, Integer selectedYear, String productCode) {

        ArrayList<Job> jobs = new ArrayList<Job>();
        String expression = selectedYear.toString() + "-";
        if (selectedMonth < 10) {
            expression += "0" + selectedMonth.toString();
        } else {
            expression += selectedMonth.toString();
        }
        ArrayList<SalesOrder> salesOrders = new ArrayList(getSalesOrders("Approved"));
        Boolean found = false;
        for (SalesOrder so : salesOrders) {
            ArrayList<PurchaseItem> purchaseItems = new ArrayList(so.getJob().getPurchaseOrder().getPurchaseItems());

            for (PurchaseItem poi : purchaseItems) {
                DateFormat df;
                df = new SimpleDateFormat("yyyy-MM-dd");
                String date = df.format(poi.getRequestDate());

                if (date.toString().contains(expression) && poi.getProduct().getCode().compareTo(productCode) == 0) {

                    found = true;    //job contains purchase item which requested date is selected by user
                }
            }
            if (found) {
                jobs.add(so.getJob());
                found = false;
            }

        }
        return jobs;
    }

    @Override
    public void failSalesOrderCreditCheck(Long id) {
        SalesOrder salesOrder = entityManager.find(SalesOrder.class, id);
        Job job = entityManager.find(Job.class, salesOrder.getJob().getJobId());
        PurchaseOrder purchaseOrder = entityManager.find(PurchaseOrder.class, job.getPurchaseOrder().getId());
        Quotation quotation = entityManager.find(Quotation.class, job.getSelectedQuotation().getId());

        quotation.setStatus("Active");
        purchaseOrder.setStatus("Invalid");
        job.setPurchaseOrder(null);
        job.setSelectedQuotation(null);
        salesOrder.setStatus("Failed Credit Check");
        salesOrder.setCreditCheck("Failed");

        entityManager.persist(quotation);
        entityManager.persist(purchaseOrder);
        entityManager.persist(job);
        entityManager.persist(salesOrder);
        entityManager.flush();
    }

    @Override
    public void passSalesOrderCreditCheck(Long id) {
        SalesOrder salesOrder = entityManager.find(SalesOrder.class, id);

        salesOrder.setStatus("Pending ATP Check");
        salesOrder.setCreditCheck("Passed");

        entityManager.persist(salesOrder);
        entityManager.flush();
    }

    @Override
    public ArrayList<SalesOrder> getSalesOrders(String userId, String status) {
        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s");

        ArrayList<SalesOrder> salesOrders = new ArrayList<SalesOrder>();

        for (Object o : query.getResultList()) {
            SalesOrder s = (SalesOrder) o;
            
            if (s.getJob().getEmployee().getUserId().equals(userId)) {
                if (s.getStatus().contains(status)) {
                    
                    System.out.println(s + "object");
                    System.out.println(s.getJob().getEmployee() + "employee");
                    System.out.println(s.getJob().getEmployee().getUserId() + "userid");
                    
                    salesOrders.add(s);
                }
            }
            
            
        }

        return salesOrders;
    }

    @Override
    public SalesOrder getSalesOrder(Long id) {
        SalesOrder salesOrder = entityManager.find(SalesOrder.class, id);

        return salesOrder;
    }
    
    @Override
    public void updateAtpStatus (Long id, String status)
    {
        SalesOrder salesOrder = entityManager.find(SalesOrder.class, id);
        salesOrder.setAtpCheck(status);
        entityManager.persist(salesOrder);
        entityManager.flush();
    }
}
